<?php
/**
 * GrandMedia Database Class
 * 
 */
class gMDb {

    var $query;				// User passed query
    var $resultPerPage;		// Total records in each pages
    var $totalResult;		// Total records in DB
    var $pages;				// Total number of pages required
    var $openPage;			// currently opened page
    var $selectedMedia;			// currently opened page

	/**
	* Get Wordpress Media
	*/
	function get_wp_media_lib( $arg = array('mime_type'=>'','orderby'=>'ID','order'=>'','limit'=>'0','filter'=>'','s'=>'') ) {
		global $wpdb;
		extract($arg);
		$and = '';
		$ord = '';
		$lim = '';
        $search = '';
		$sel_ids = array();
		if(isset($_POST['selected_items'])){
			$sel_ids = explode(',',$_POST['selected_items']);
			$sel_ids = array_filter($sel_ids, 'is_numeric');
		} elseif(isset($_COOKIE['gmedia_selected_items'])){
			$sel_ids = explode(',',$_COOKIE['gmedia_selected_items']);
			$sel_ids = array_filter($sel_ids, 'is_numeric');
		}
		$this->selectedMedia = $sel_ids;
		switch($mime_type) {
			case 'image':
				$and .= " AND post_mime_type REGEXP '^image(.*)'";
			break;
			case 'audio':
				$and .= " AND post_mime_type = 'audio/mpeg'";
			break;
		  	case 'video':
				$and .= " AND post_mime_type REGEXP 'flv|flash'";
			break;
		  	case 'other':
				$and .= " AND post_mime_type NOT REGEXP 'flv|flash|image|audio'";
			break;
		}
        // If a search pattern is specified, load the posts that match
        if ( !empty($s) ) {
            // added slashes screw with quote grouping when done early, so done later
            $s = stripslashes($s);

            // split the words it a array if seperated by a space or comma
            preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches);
            $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);

            $n = '%';
            $searchand = '';

            foreach( (array) $search_terms as $term) {
                $term = addslashes_gpc($term);
                $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}'))";
                $searchand = ' AND ';
            }

            $term = $wpdb->escape($s);
            if (count($search_terms) > 1 && $search_terms[0] != $s )
                $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}')";

            if ( !empty($search) )
                $search = " AND ({$search}) ";
		}
		if($orderby) {
			switch($orderby){
				case 'ID':
					$orderby = 'ID';
					if(!$order) $order = 'DESC';
				break;
				case 'filename':
					$orderby = 'post_name';
				break;
				case 'title':
					$orderby = 'post_title';
				break;
				case 'date':
					$orderby = 'post_modified';
				break;
				case 'selected':
					if(count($sel_ids) > 1) {
						$orderby = 'FIELD(ID, '.join(', ', $sel_ids).')';
					} else {
						$orderby = 'ID';
					}
				break;
				default:
					$orderby = preg_replace('/[^a-z_]/', ' ', $orderby);
				break;
			}
			$ord .= " ORDER BY {$orderby}";
			$ord .= ($order == 'DESC')? ' DESC' : ' ASC';
		}
		switch($filter){
			case 'hidden':
				$filter = "AND EXISTS ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = '_gmedia_hidden' )";
			break;
			case 'selected':
				if(count($sel_ids)) {
					$and .= ' AND ID IN ('.join(', ', $sel_ids).')';
					$filter = "";
					break;
				} else {
					// message: No selected items
				}
			default:
				$filter = "AND NOT EXISTS ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = '_gmedia_hidden' )";
			break;
		}
		$this->openPage = grandCore::_get('pager','1');
		$this->resultPerPage = $limit;
		if( $limit > 0 ) {
			$limit = intval($limit);
			$offset = ($this->openPage - 1)*$limit;
			$lim .= " LIMIT {$offset}, {$limit}";
		}
		$this->query = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id) WHERE post_type = 'attachment' {$filter} {$and} {$search} GROUP BY ID {$ord} {$lim}");
		$this->totalResult = $wpdb->get_var("SELECT FOUND_ROWS()");
		if( $limit == 0 )
			$limit = $this->totalResult;
       	$this->pages = ceil($this->totalResult/$limit);
        if($this->openPage > $this->pages) 
			$this->openPage = $this->pages;
		return $this->query;
	}
	
	/**
	 * function to display the pagination
	 */
    function queryPager() {
    	if($this->pages == 1)
			return '';
		$params = $_GET;
		unset($params["pager"]);
		$new_query_string = http_build_query($params);
        $self = admin_url('admin.php?'.$new_query_string);
        if($this->openPage<=0)
            $next = 2;
        else
            $next = $this->openPage+1;
        $prev = $this->openPage-1;
        $last = $this->pages;
		$result = '<form name="grandPager" method="get" class="grandPager"><span class="pager_total_items">'.$this->totalResult.' '.__("items","gmLang").'</span>';

        if($this->openPage > 1) {
           	$result .= "<a class='pager_first' href='{$self}'>«</a>";
            $result .= "<a class='pager_prev' href='{$self}&pager=$prev'>‹</a>";
        } else {
           	$result .= "<span class='pager_first'>«</span>";
            $result .= "<span class='pager_prev'>‹</span>";
        }
		$result .= '<div class="pager_pages">';
		foreach($params as $key => $value) {
			$result .= '<input type="hidden" name="'.$key.'" value="'.$value.'" />';
		}
		$result .= '<input class="pager_current_page" name="pager" type="text" value="'.$this->openPage.'" /><span class="pager_total_pages">'.__("of","gmLang").' '.$this->pages.'</div>';
        if($this->openPage < $this->pages) {
            $result .= "<a class='pager_next' href='{$self}&pager=$next'>›</a>";
           	$result .= "<a class='pager_last' href='{$self}&pager=$last'>»</a>";
        } else {
            $result .= "<span class='pager_next'>›</span>";
           	$result .= "<span class='pager_last'>»</span>";
        }
		$result .= '</form>';
		return $result;
    }
	
	function mediaCount($arg) {
		global $wpdb;
		extract($arg);
		$search = '';
		switch($filter){
			case 'hidden':
				$filter = "AND EXISTS ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = '_gmedia_hidden' )";
			break;
			case 'selected':
				if(count($this->selectedMedia)) {
					$filter = ' AND ID IN ('.join(', ', $this->selectedMedia).')';
					break;
				}
			default:
				$filter = "AND NOT EXISTS ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = '_gmedia_hidden' )";
			break;
		}
        // If a search pattern is specified, load the posts that match
        if ( !empty($s) ) {
            // added slashes screw with quote grouping when done early, so done later
            $s = stripslashes($s);

            // split the words it a array if seperated by a space or comma
            preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches);
            $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);

            $n = '%';
            $searchand = '';

            foreach( (array) $search_terms as $term) {
                $term = addslashes_gpc($term);
                $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}'))";
                $searchand = ' AND ';
            }

            $term = $wpdb->escape($s);
            if (count($search_terms) > 1 && $search_terms[0] != $s )
                $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_name LIKE '{$n}{$term}{$n}')";

            if ( !empty($search) )
                $search = " AND ({$search}) ";

		}
		$count['hidden'] 	= $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_key = '_gmedia_hidden' {$search}");
		$count['all'] 		= $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' {$filter} {$search}");
		$count['image'] 	= $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' {$filter} AND post_mime_type REGEXP '^image(.*)' {$search}");
		$count['audio'] 	= $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' {$filter} AND post_mime_type = 'audio/mpeg' {$search}");
		$count['video'] 	= $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' {$filter} AND post_mime_type REGEXP 'flv|flash' {$search}");
		$count['other'] 	= $count['all'] - ($count['image'] + $count['audio'] + $count['video']);
		return $count;
	}
}

global $gMDb;
$gMDb = new gMDb;

?>